using Basis;
using UnityEngine;

namespace NL.Advanced
{

    public interface IRudderOwner
    {
        float Life { get; }
        Vector3 Speeding { get; set; }
        Target Target { get; }
    }

    public class Rudder : MonoBehaviour
    {
        [Header("方向速度")]
        public float TurnSpeed = 1800;


        [Header("目标定位周期")]
        public float RePosition = 0.1f;

        float _TurningSpeed = 0;
        IRudderOwner _Owner;
        float _Lifing = 0;
        Vector3 _TargetPos;
        float _LastReposition = 0;
        private void OnEnable()
        {
            _Owner = GetComponent<IRudderOwner>();
            _TurningSpeed = TurnSpeed;
            _Lifing = 0;
            _LastReposition = float.MinValue;
        }
        // Update is called once per frame
        protected virtual void Update()
        {
            if (_Owner == null) return;

            if (!_Owner.Target.Exist) return;

            _Lifing += Time.deltaTime;
            if (_Lifing > 5)
            {
                _TurningSpeed *= 1.1f;
            }

            //重新定位
            if (Time.time - _LastReposition > RePosition)
            {
                _TargetPos = _Owner.Target.Position;
                _LastReposition = Time.time;
            }



            Vector3 _dir = (_TargetPos - transform.position).normalized;

            Vector3 _speeding = _Owner.Speeding;


            float t = _dir.magnitude / _speeding.magnitude;

            float dt = t - _Owner.Life;
            if (50 * dt > -5)
            {
                _TurningSpeed = _TurningSpeed * (1 + 0.4f / (5 + 50 * dt));
            }


            //处理 方向舵.
            if (_TurningSpeed > 0)
            {

                float _tangle = Mathf.Abs(Vector3.Angle(_speeding, _dir));

                float _dangle = _TurningSpeed * Time.deltaTime;

                if (_dangle > _tangle)
                    _dangle = _tangle;



                Vector3 _axis = Vector3.Cross(_speeding, _dir);
                Quaternion Q = Quaternion.AngleAxis(_dangle, _axis);

                _speeding = Q * _speeding;
                _Owner.Speeding = _speeding;
            }




            //float _speed = _speeding.magnitude;

            //_speed += Accelerate * Time.deltaTime;

            //_Owner.Speeding= _speeding.normalized * _speed;

        }
    }

}
